package com.sun.tools.xjc.addons.android_plugin;

import java.util.Map;

import com.sun.codemodel.JAnnotationUse;
import com.sun.codemodel.JAnnotationValue;
import com.sun.codemodel.JFieldVar;
import com.sun.codemodel.JStringLiteral;

public class APXmlAttribute {
  public String variableName;
  public String name;
  public String namespace;
  public JFieldVar field;
  
  // TODO: required

  public APXmlAttribute() {
    variableName = "";
    name = "";
    namespace = "";
    field = null;
  }
  
  public APXmlAttribute(JAnnotationUse xmlAnnotation, String name, JFieldVar field) 
  throws Exception {
    this.field = field;
    this.variableName = name;
    this.name = "";
    this.namespace = "";
    
    String annotationName = xmlAnnotation.getAnnotationClass().name();

    if(annotationName.equals("XmlAttribute")) {
      Object[] info =
          getNameAndNamespaceFromXmlAttributeAnnotation(xmlAnnotation);
      this.name = (String)info[0];
      this.namespace = (String)info[1];
    } else {
      throw new Exception("Annotation is not of type XmlAttribute");
    }
  }

  private static Object[] getNameAndNamespaceFromXmlAttributeAnnotation(
      JAnnotationUse xmlAttributeAnnotation) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
    Object[] objs = new Object[2];
    
    Map<String, JAnnotationValue> memberMap = 
        xmlAttributeAnnotation.getAnnotationMembers();
    
    if(memberMap.containsKey("name")) {
      JAnnotationValue val = memberMap.get("name");
      JStringLiteral jval = Utilities.getFieldValue(val, "value");
      objs[0] = jval.str;
    } else {
      objs[0] = null;
    }
    
    if(memberMap.containsKey("namespace")) {
      JAnnotationValue val = memberMap.get("namespace");
      JStringLiteral jval = Utilities.getFieldValue(val, "value");
      objs[1] = jval.str;
    } else {
      objs[1] = null;
    }
    
    return objs;
  }
  
}

